//index.js

//获取应用实例
const app = getApp()
const base64 = require('../../utils/base64.js')
// const orgAPI = require('../../api/organization.js')

Page({
  data: {
    motto: 'Incident Communication',
    motto_sub: 'Lite',
    envIndex: 0,
    envList: [
      { 'name': 'QA1', 'value': 'https://wx.ipartyzone.com/' },
      { 'name': 'Stage', 'value': 'https://api-stage.everbridge.net/' },
      { 'name': 'Production', 'value': 'https://api.everbridge.net/' }
    ],
    userInfo: {},
    orgList: [],
    orgIndex: 0,
    hasOrgInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  bindEnvChange: function (event) {
    this.setData({
      envIndex: event.detail.value
    });
    wx.setStorage({
      key: 'envIndex',
      data: event.detail.value,
    })

  },
  onLoginSubmit: function (event) {
    const that = this;
    const { userName, password } = event.detail.value;
    wx.setStorage({
      key: 'userInfo',
      data: {
        userName: userName,
        password: password,
      },
    })
    let auth = 'Basic ' + base64.encode(`${userName}:${password}`);
    app.globalData.authentication = auth;

    wx.showLoading({
      title: 'Loading',
    })

    wx.request({
      url: app.globalData.requestPrefix + 'rest/organizations',
      header: {
        'content-type': 'application/json',
        'Authorization': auth
      },
      fail: function(res) {
        wx.showModal({
          title: 'Error',
          content: res.errMsg
        })
      },
      complete: function(res){
        wx.hideLoading();
      },
      success: function (res) {
        if (res.statusCode !== 200) {
          wx.showModal({
            title: 'Error',
            content: res.data.message
          })
          return;
        }
        const orgList = res.data.page.data.map(function (item) {
          return {
            name: item.name,
            id: item.id
          }
        });
        if (orgList.length > 0) {
          that.setData({
            'orgList': orgList,
            'hasOrgInfo': true,
          });
        }
      }
    })
  },
  bindOrgChange: function (event) {
    let currentOrgId = this.data.orgList[event.detail.value].id;
    app.globalData.currentOrg = currentOrgId;
    wx.navigateBack({
      url: '../template/template',
    })
  },
  onLoad: function () {
    var that = this;
    let apiURLPrefix = this.data['envList'][this.data['envIndex']]['value'];
    app.globalData.requestPrefix = apiURLPrefix;

    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data,
          hasUserInfo: true
        })
      },
    })
    wx.getStorage({
      key: 'envIndex',
      success: function (res) {
        that.setData({
          envIndex: parseInt(res.data, 10) || 0
        })
      },
    })
  }
})
